<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 加载状态 -->
      <div v-if="loading" class="flex flex-col items-center justify-center py-20">
        <div class="animate-spin rounded-full h-16 w-16 border-4 border-blue-600 border-t-transparent"></div>
        <span class="mt-4 text-lg text-gray-600">加载竞赛信息中...</span>
      </div>

      <!-- 竞赛不存在提示 -->
      <div v-else-if="contestNotFound" class="flex flex-col items-center justify-center py-20">
        <div class="text-center">
          <div class="w-32 h-32 mx-auto mb-8 bg-gradient-to-br from-red-100 to-pink-100 rounded-full flex items-center justify-center">
            <svg class="w-16 h-16 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
            </svg>
          </div>
          <h2 class="text-3xl font-bold text-gray-900 mb-4">竞赛不存在</h2>
          <p class="text-gray-600 mb-8 text-lg">抱歉，您访问的竞赛不存在或已被删除。</p>
          <button 
            @click="$router.push('/contests')"
            class="bg-gradient-to-r from-blue-600 to-purple-600 text-white px-8 py-4 rounded-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 shadow-lg hover:shadow-xl transform hover:scale-105"
          >
            返回竞赛列表
          </button>
        </div>
      </div>

      <!-- 竞赛内容 -->
      <div v-else>
        <!-- 竞赛头部信息 -->
        <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl p-8 mb-8 border border-white/20">
          <div class="flex flex-col lg:flex-row lg:items-center justify-between mb-6">
            <div class="flex-1">
              <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-3">{{ contest?.title }}</h1>
              <p class="text-gray-600 text-lg leading-relaxed">{{ contest?.description || '暂无描述' }}</p>
            </div>
            <div class="mt-4 lg:mt-0 lg:ml-6">
              <span
                :class="[
                  'inline-flex items-center px-6 py-3 rounded-full text-lg font-semibold shadow-lg',
                  contest?.status === 'upcoming' ? 'bg-gradient-to-r from-blue-100 to-blue-200 text-blue-800' :
                  contest?.status === 'running' ? 'bg-gradient-to-r from-green-100 to-green-200 text-green-800' :
                  'bg-gradient-to-r from-gray-100 to-gray-200 text-gray-800'
                ]"
              >
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                {{ contest?.status === 'upcoming' ? '即将开始' : contest?.status === 'running' ? '进行中' : '已结束' }}
              </span>
            </div>
          </div>
          
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
            <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-xl">
              <div class="flex items-center mb-2">
                <svg class="w-5 h-5 text-blue-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path>
                </svg>
                <span class="text-sm font-medium text-blue-700">开始时间</span>
              </div>
              <div class="text-lg font-bold text-blue-900">{{ formatDateTime(contest?.start_time) }}</div>
            </div>
            
            <div class="bg-gradient-to-br from-red-50 to-red-100 p-4 rounded-xl">
              <div class="flex items-center mb-2">
                <svg class="w-5 h-5 text-red-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span class="text-sm font-medium text-red-700">结束时间</span>
              </div>
              <div class="text-lg font-bold text-red-900">{{ formatDateTime(contest?.end_time) }}</div>
            </div>
            
            <div class="bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-xl">
              <div class="flex items-center mb-2">
                <svg class="w-5 h-5 text-green-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <span class="text-sm font-medium text-green-700">竞赛时长</span>
              </div>
              <div class="text-lg font-bold text-green-900">{{ contest?.duration }} 分钟</div>
            </div>
            
            <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-4 rounded-xl">
              <div class="flex items-center mb-2">
                <svg class="w-5 h-5 text-purple-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                </svg>
                <span class="text-sm font-medium text-purple-700">参赛人数</span>
              </div>
              <div class="text-lg font-bold text-purple-900">{{ contest?.participant_count || 0 }}</div>
            </div>
          </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <!-- 左侧：题目列表 -->
          <div class="lg:col-span-2">
            <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-white/20">
              <div class="p-6 border-b border-gray-200">
                <div class="flex items-center justify-between">
                  <h2 class="text-2xl font-bold text-gray-900">题目列表</h2>
                  <span class="text-sm text-gray-500">{{ problems.length }} 道题目</span>
                </div>
              </div>
              
              <!-- 无题目提示 -->
              <div v-if="problems.length === 0" class="p-12 text-center">
                <div class="w-24 h-24 mx-auto mb-6 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                  <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                  </svg>
                </div>
                <h3 class="text-xl font-semibold text-gray-900 mb-2">暂无题目</h3>
                <p class="text-gray-600">该竞赛还没有添加题目，请稍后再来查看。</p>
              </div>
              
              <!-- 题目列表 -->
              <div v-else class="divide-y divide-gray-200">
                <div
                  v-for="(problem, index) in problems"
                  :key="problem.id"
                  class="p-6 hover:bg-gradient-to-r hover:from-blue-50 hover:to-indigo-50 cursor-pointer transition-all duration-200"
                  @click="selectProblem(problem)"
                >
                  <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                      <div class="flex items-center gap-3">
                        <span class="text-2xl font-bold text-gray-900">{{ String.fromCharCode(65 + index) }}</span>
                        <span
                          :class="[
                            'w-4 h-4 rounded-full',
                            problem.status === 'solved' ? 'bg-green-500' :
                            problem.status === 'attempted' ? 'bg-yellow-500' :
                            'bg-gray-300'
                          ]"
                        ></span>
                      </div>
                      
                      <div>
                        <h3 class="text-lg font-semibold text-gray-900 mb-1">{{ problem.title }}</h3>
                        <p class="text-sm text-gray-600">{{ problem.description }}</p>
                        <div class="flex items-center gap-4 mt-2">
                          <span 
                            :class="[
                              'px-2 py-1 rounded-full text-xs font-medium',
                              problem.difficulty === 'Easy' ? 'bg-green-100 text-green-800' :
                              problem.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' :
                              'bg-red-100 text-red-800'
                            ]"
                          >
                            {{ problem.difficulty === 'Easy' ? '简单' : problem.difficulty === 'Medium' ? '中等' : '困难' }}
                          </span>
                        </div>
                      </div>
                    </div>
                    
                    <div class="flex items-center gap-6 text-sm text-gray-500">
                      <div class="text-center">
                        <div class="font-semibold">{{ problem.acceptance }}%</div>
                        <div class="text-xs">通过率</div>
                      </div>
                      <div class="text-center">
                        <div class="font-semibold">{{ problem.solvedCount }}</div>
                        <div class="text-xs">人通过</div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：排行榜和统计 -->
          <div class="lg:col-span-1 space-y-6">
            <!-- 排行榜 -->
            <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-white/20">
              <div class="p-6 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-900">实时排行榜</h2>
              </div>
              
              <div class="p-6">
                <div v-if="leaderboard.length === 0" class="text-center py-8">
                  <div class="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-gray-100 to-gray-200 rounded-full flex items-center justify-center">
                    <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
                    </svg>
                  </div>
                  <p class="text-gray-600">暂无排行榜数据</p>
                </div>
                
                <div v-else class="space-y-3">
                  <div
                    v-for="(user, index) in leaderboard"
                    :key="user.id"
                    class="flex items-center justify-between p-3 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <div class="flex items-center gap-3">
                      <span
                        :class="[
                          'w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold',
                          index < 3 ? 'bg-gradient-to-r from-yellow-400 to-orange-500 text-white' : 'bg-gray-100 text-gray-600'
                        ]"
                      >
                        {{ index + 1 }}
                      </span>
                      <div class="w-8 h-8 bg-gradient-to-br from-blue-400 to-purple-500 rounded-full flex items-center justify-center">
                        <span class="text-white font-bold text-sm">{{ user.username.charAt(0).toUpperCase() }}</span>
                      </div>
                      <span class="font-medium text-gray-900">{{ user.username }}</span>
                    </div>
                    <div class="text-sm font-semibold text-gray-700">
                      {{ user.score }} 分
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 我的统计 -->
            <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-white/20">
              <div class="p-6 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-900">我的统计</h2>
              </div>
              
              <div class="p-6">
                <div class="space-y-4">
                  <div class="flex justify-between items-center">
                    <span class="text-gray-600">排名:</span>
                    <span class="font-bold text-lg">{{ myStats.rank || '未参与' }}</span>
                  </div>
                  <div class="flex justify-between items-center">
                    <span class="text-gray-600">得分:</span>
                    <span class="font-bold text-lg text-blue-600">{{ myStats.score || 0 }} 分</span>
                  </div>
                  <div class="flex justify-between items-center">
                    <span class="text-gray-600">通过题目:</span>
                    <span class="font-bold text-lg text-green-600">{{ myStats.solved || 0 }}/{{ problems.length }}</span>
                  </div>
                  <div class="flex justify-between items-center">
                    <span class="text-gray-600">提交次数:</span>
                    <span class="font-bold text-lg text-purple-600">{{ myStats.submissions || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 竞赛规则 -->
            <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-xl border border-white/20">
              <div class="p-6 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-900">竞赛规则</h2>
              </div>
              
              <div class="p-6">
                <ul class="space-y-3 text-sm text-gray-600">
                  <li class="flex items-start">
                    <span class="w-2 h-2 bg-blue-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    竞赛时长 {{ contest?.duration }} 分钟
                  </li>
                  <li class="flex items-start">
                    <span class="w-2 h-2 bg-green-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    共 {{ problems.length }} 道题目
                  </li>
                  <li class="flex items-start">
                    <span class="w-2 h-2 bg-yellow-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    每题分值根据难度递增
                  </li>
                  <li class="flex items-start">
                    <span class="w-2 h-2 bg-purple-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    按通过题目数和用时排名
                  </li>
                  <li class="flex items-start">
                    <span class="w-2 h-2 bg-red-500 rounded-full mt-2 mr-3 flex-shrink-0"></span>
                    禁止作弊，违者取消成绩
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getContest, getContestRanking, type Contest } from '@/api/contest'

const route = useRoute()
const router = useRouter()

// 响应式数据
const contest = ref<Contest | null>(null)
const loading = ref(true)
const contestNotFound = ref(false)
const problems = ref<any[]>([])
const leaderboard = ref<any[]>([])
const myStats = ref({
  rank: null as number | null,
  score: 0,
  solved: 0,
  submissions: 0
})

// 加载竞赛数据
const loadContest = async () => {
  try {
    loading.value = true
    const contestId = parseInt(route.params.id as string)
    
    if (isNaN(contestId)) {
      contestNotFound.value = true
      return
    }

    const response = await getContest(contestId)
    
    // 检查返回的数据是否为字符串（竞赛不存在的情况）
    if (typeof response.data === 'string' && (response.data as string).includes('竞赛不存在')) {
      contestNotFound.value = true
      return
    }
    
    contest.value = response.data
    
    // 加载竞赛题目
    await loadContestProblems(contestId)
    
    // 加载排行榜
    await loadContestRanking(contestId)
    
  } catch (error) {
    console.error('加载竞赛失败:', error)
    contestNotFound.value = true
  } finally {
    loading.value = false
  }
}

// 加载竞赛题目
const loadContestProblems = async (contestId: number) => {
  try {
    // 这里应该调用获取竞赛题目的API
    // 暂时使用空数组，等待后端API实现
    problems.value = []
    console.log('加载竞赛题目:', contestId)
  } catch (error) {
    console.error('加载竞赛题目失败:', error)
    problems.value = []
  }
}

// 加载竞赛排行榜
const loadContestRanking = async (contestId: number) => {
  try {
    const response = await getContestRanking(contestId)
    leaderboard.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    console.error('加载竞赛排行榜失败:', error)
    leaderboard.value = []
  }
}

// 方法
const selectProblem = (problem: any) => {
  // 跳转到题目详情页面
  router.push(`/contests/${contest.value?.id}/problems/${problem.id}`)
}

const formatDateTime = (dateString: string | undefined) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadContest()
})
</script>
